package com.mywork.mvpkodeingithub.presenter

import com.mywork.mvpkodeingithub.base.presenter.BasePresenter
import com.mywork.mvpkodeingithub.common.execute
import com.mywork.mvpkodeingithub.data.response.Repo
import com.mywork.mvpkodeingithub.data.response.User
import com.mywork.mvpkodeingithub.repository.GithubRepository
import com.mywork.mvpkodeingithub.repository.GithubRepository.Companion.PAGE_COUNT
import com.mywork.mvpkodeingithub.rx.BaseSubscriber
import com.mywork.mvpkodeingithub.view.MainView
import io.rx_cache2.Reply
import org.kodein.di.Kodein
import org.kodein.di.generic.instance

class MainPresenter(kodein: Kodein) : BasePresenter<MainView>(kodein) {

    //Inject
    override val mView: MainView by kodein.instance()
    private var lastUserId = 0

    //Inject
    val githubRepository: GithubRepository by kodein.instance()

    fun getUsers(pullToRefresh: Boolean) {
        if (pullToRefresh) {
            lastUserId = 0
        }
        githubRepository.getUsers(lastUserId, pullToRefresh)
            .execute(mView, lifecycleOwner, object : BaseSubscriber<Reply<List<User>>>(mView) {
                override fun onNext(t: Reply<List<User>>) {
                    mView.onGetUsers(t.data, t.source.toString())
                    lastUserId = lastUserId + PAGE_COUNT
                }

            })
    }

    fun getRepos(userName: String) {
        var isUpdate: Boolean = true
        if (!checkNetwork()) {
            isUpdate = false
        }
        githubRepository.getRepos(userName, isUpdate)
            .execute(mView, lifecycleOwner, object : BaseSubscriber<Reply<List<Repo>>>(mView) {
                override fun onNext(t: Reply<List<Repo>>) {
                    mView.onGetRepo(t.data, t.source.toString())
                }

            })
    }


}